<?
// Funcion que los sms
function send_sms($tm_login,$tm_password,$tm_to,$tm_mensaje) {
    # variable
    $host = 'opensms.movistar.es';
    $service_uri = '/aplicacionpost/loginEnvio.jsp';
    $vars ="TM_ACTION=AUTHENTICATE&TM_LOGIN=".$tm_login."&TM_PASSWORD=".$tm_password."&to=".$tm_to."&message=".$tm_mensaje;

    # cabecera http HTTP 
    $header = "Host: $host\r\n";
    $header .= "User-Agent: PHP Script\r\n";
    $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
    $header .= "Content-Length: ".strlen($vars)."\r\n";
    $header .= "Connection: close\r\n\r\n";

    $fp = pfsockopen($host, 443, $errno, $errstr);

if (!$fp) {
   echo "$errstr ($errno)<br/>\n";
   echo $fp;
} else {
    fputs($fp, "POST $service_uri  HTTP/1.1\r\n");
    fputs($fp, $header.$vars);
    fwrite($fp, $out);
    /* muestra la salida (opcional)
    while (!feof($fp)) {
        echo fgets($fp, 128);
    }
    */
    fclose($fp);
}
}

$db_host = "localhost";
$db_user = "twitteromf";
$db_password = "uJYY9EHKCFVNpBRD";
//$db_selectdb = "drupal56";
$db_selectdb = "omf";

$link = mysql_connect($db_host, $db_user, $db_password);
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db($db_selectdb, $link) or die('Could not select database.');

//abrimos la sesion imap
$mbox = imap_open("{imap.gmail.com:993/imap/ssl}", "twitteromf", ".admin33.mf.");

//buscamos correos de la api
echo "Procesando los sms.................\n";
$nuevos = imap_search($mbox,'TEXT "Texto:"');

if ($nuevos == false) {
    echo "No hay ningun sms\n";
} else {
    foreach ($nuevos as $val) {
        echo "\n";

	// procesamos los datos
	$mensaje = imap_body($mbox,$val,'FT_UID');
	$procesado = explode("\n", $mensaje);
	$msisdn = explode(":", $procesado[0]);
	$texto = explode(":", $procesado[1]);

	// validamos el remitente
	$solo9 = substr($msisdn[1], -9);
	$result = mysql_query("select uid from profile_values where value like '%$solo9'");
	while ($row = mysql_fetch_row($result)) {
    	$uid = $row['0'];
    	}

	$result = mysql_query("select name from users where uid = '$uid'");
	while ($row = mysql_fetch_row($result)) {
    	$name = $row['0'];
    	}

	if (isset($uid)) { 
	// insertamos en el xml privado
	$fecha = date(DATE_RFC822); 
	$xml = simplexml_load_file('xml/log.xml');
	$twit = $xml->addChild('twit');
	$twit->addChild('from', $name);
	$twit->addChild('msisdn', $msisdn[1]);
	$twit->addChild('body', $texto[1]);
	$twit->addChild('date', $fecha);
	$twit->addChild('userid', $uid);
	$twit->addChild('blocked', 0);
	$xml->asXML('xml/log.xml');
	} else {
	echo "No se reconoce el remitente";
	}


	//enviamos los sms los resultados
	//$envio = send_sms("666777888","clave770","666777999", $texto[1]);
	imap_delete($mbox, $val, 'FT_UID');
	//echo $msisdn[1] ."\n";
	//echo $texto[1];
    }
}
imap_close($mbox);
?>
